<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>翻译功能测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .test-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .language-selector {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .language-btn {
            padding: 8px 16px;
            border: 2px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            background: white;
        }
        .language-btn.active {
            background: #007bff;
            color: white;
        }
        .test-item {
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 4px;
        }
        .original {
            font-weight: bold;
            color: #333;
        }
        .translated {
            color: #007bff;
            margin-top: 10px;
            font-style: italic;
        }
        .loading {
            color: #666;
            font-style: italic;
        }
        .error {
            color: #dc3545;
        }
        .debug-info {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
    <h1>翻译功能测试</h1>
    
    <div class="test-container">
        <h2>语言选择</h2>
        <div class="language-selector">
            <button class="language-btn active" onclick="setLanguage('zh')">中文</button>
            <button class="language-btn" onclick="setLanguage('en')">English</button>
            <button class="language-btn" onclick="setLanguage('pt')">Português</button>
        </div>
        <div id="currentLanguage">当前语言: 中文</div>
    </div>

    <div class="test-container">
        <h2>翻译测试</h2>
        <div id="testResults"></div>
        <button onclick="runTranslationTest()">运行翻译测试</button>
    </div>

    <div class="test-container">
        <h2>调试信息</h2>
        <div id="debugInfo"></div>
    </div>

    <script>
        let currentLanguage = 'zh';
        
        // 模拟翻译服务
        class TranslationService {
            constructor() {
                this.cache = new Map();
                this.isLoading = false;
            }

            async translate(text, targetLang, sourceLang = 'zh') {
                if (targetLang === sourceLang) return text;
                
                const cacheKey = `${sourceLang}-${targetLang}-${text}`;
                if (this.cache.has(cacheKey)) {
                    return this.cache.get(cacheKey);
                }

                this.isLoading = true;
                
                try {
                    // 首先尝试百度翻译
                    const result = await this.translateWithBaidu(text, targetLang, sourceLang);
                    this.cache.set(cacheKey, result);
                    return result;
                } catch (error) {
                    console.error('翻译失败:', error);
                    return text;
                } finally {
                    this.isLoading = false;
                }
            }

            async translateWithBaidu(text, targetLang, sourceLang = 'zh') {
                const appId = '20250627002391301';
                const appKey = 'ZPM1rdKh_etnWFatwYR0';
                const salt = Date.now().toString();
                const query = text;
                const from = this.getBaiduLangCode(sourceLang);
                const to = this.getBaiduLangCode(targetLang);
                
                // 生成MD5签名
                const signStr = appId + query + salt + appKey;
                const sign = await this.md5(signStr);
                
                const url = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
                const params = new URLSearchParams({
                    q: query,
                    from,
                    to,
                    appid: appId,
                    salt,
                    sign
                });

                const response = await fetch(`${url}?${params}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                if (data.trans_result && data.trans_result.length > 0) {
                    return data.trans_result[0].dst;
                }
                
                if (data.error_code) {
                    throw new Error(`百度翻译错误: ${data.error_msg}`);
                }
                
                throw new Error('百度翻译失败');
            }

            getBaiduLangCode(lang) {
                const langMap = {
                    'zh': 'zh',
                    'en': 'en',
                    'pt': 'pt'
                };
                return langMap[lang] || lang;
            }

            async md5(string) {
                const encoder = new TextEncoder();
                const data = encoder.encode(string);
                const hashBuffer = await crypto.subtle.digest('MD5', data).catch(() => {
                    // Fallback for browsers that don't support MD5
                    return this.simpleMd5(string);
                });
                
                if (typeof hashBuffer === 'string') return hashBuffer;
                
                const hashArray = Array.from(new Uint8Array(hashBuffer));
                return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
            }

            simpleMd5(str) {
                // 简单的MD5替代方案（仅用于测试）
                return btoa(str).replace(/[^a-zA-Z0-9]/g, '').substring(0, 32);
            }
        }

        const translationService = new TranslationService();

        // 测试文本
        const testTexts = [
            '跨境政策咨询平台',
            '全球政策概览',
            '智能咨询',
            '政策查询',
            '政策分析',
            '政策匹配',
            '跨境对比',
            '政策推送',
            '定时提醒',
            '个人中心',
            '欢迎回来',
            '今天是美好的一天，让我们开始工作吧！',
            '全国政策分布热力图',
            '正在加载地图数据...',
            '政策数量',
            '最新政策',
            '更新时间',
            '暂无数据',
            '高',
            '低'
        ];

        function setLanguage(lang) {
            currentLanguage = lang;
            
            // 更新按钮状态
            document.querySelectorAll('.language-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');
            
            // 更新显示
            const langNames = {
                'zh': '中文',
                'en': 'English',
                'pt': 'Português'
            };
            document.getElementById('currentLanguage').textContent = `当前语言: ${langNames[lang]}`;
            
            // 自动运行翻译测试
            runTranslationTest();
        }

        async function runTranslationTest() {
            const resultsDiv = document.getElementById('testResults');
            const debugDiv = document.getElementById('debugInfo');
            
            resultsDiv.innerHTML = '<div class="loading">正在运行翻译测试...</div>';
            debugDiv.innerHTML = '';
            
            let debugInfo = [];
            debugInfo.push(`测试语言: ${currentLanguage}`);
            debugInfo.push(`测试文本数量: ${testTexts.length}`);
            debugInfo.push(`缓存大小: ${translationService.cache.size}`);
            
            let results = [];
            
            for (let i = 0; i < testTexts.length; i++) {
                const text = testTexts[i];
                const startTime = Date.now();
                
                try {
                    const translated = await translationService.translate(text, currentLanguage, 'zh');
                    const endTime = Date.now();
                    
                    results.push({
                        original: text,
                        translated: translated,
                        success: true,
                        time: endTime - startTime
                    });
                    
                    debugInfo.push(`${text} -> ${translated} (${endTime - startTime}ms)`);
                } catch (error) {
                    results.push({
                        original: text,
                        translated: error.message,
                        success: false,
                        time: 0
                    });
                    
                    debugInfo.push(`${text} -> ERROR: ${error.message}`);
                }
            }
            
            // 显示结果
            let html = '';
            results.forEach(result => {
                html += `
                    <div class="test-item">
                        <div class="original">原文: ${result.original}</div>
                        <div class="${result.success ? 'translated' : 'error'}">
                            ${result.success ? '翻译' : '错误'}: ${result.translated}
                        </div>
                        ${result.success ? `<div class="debug-info">耗时: ${result.time}ms</div>` : ''}
                    </div>
                `;
            });
            
            resultsDiv.innerHTML = html;
            
            // 显示调试信息
            debugDiv.innerHTML = debugInfo.map(info => `<div>${info}</div>`).join('');
        }

        // 页面加载时运行测试
        window.onload = () => {
            runTranslationTest();
        };
    </script>
</body>
</html> 